import { Injectable, NotFoundException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Category } from './category.entity';


// 新增分页接口返回类型
export interface PaginatedCategoryPages {
  data: Category[];
  meta: {
    total: number;
    page: number;
    limit: number;
    totalPages: number;
  };
}


@Injectable()
export class CategoryService {
  constructor(
    @InjectRepository(Category)
    private categoryRepository: Repository<Category>,
  ) { }

  // 添加新类别
  async createCategory(name: string, coverImg?: string, description?: string, images?: Record<string, any>, is_visible?: boolean): Promise<Category> {
    const category = this.categoryRepository.create({
      name,
      cover_img: coverImg,
      description,
      is_visible: is_visible || true, // 默认可见
      images: images || [], // 初始化空数组
    });
    return this.categoryRepository.save(category);
  }

  // 更新类别信息
  async updateCategory(
    id: number,
    updates: {
      name?: string;
      coverImg?: string;
      description?: string;
      images?: Array<Record<string, any>>; // 支持自由格式图片数组
      is_visible?: boolean;
    },
  ): Promise<Category> {
    const category = await this.categoryRepository.findOne({ where: { id } });
    if (!category) {
      throw new NotFoundException(`Category with ID ${id} not found`);
    }

    // 合并更新字段（保留未修改的原始值）
    const updatedCategory = this.categoryRepository.merge(category, updates);
    return this.categoryRepository.save(updatedCategory);
  }


  // 删除类别（需确保无关联设计页面）
  async deleteCategory(id: number): Promise<void> {
    const category = await this.categoryRepository.findOne({
      where: { id },
      relations: ['pages'], // 检查关联的设计页面
    });

    if (!category) {
      throw new NotFoundException(`Category with ID ${id} not found`);
    }

    if (category.pages.length > 0) {
      throw new NotFoundException('Cannot delete category with associated design pages');
    }

    await this.categoryRepository.delete(id);
  }

  // 切换类别显示/隐藏状态
  async toggleVisibility(id: number, visible: boolean): Promise<Category> {
    const category = await this.categoryRepository.findOne({ where: { id } });
    if (!category) {
      throw new NotFoundException(`Category with ID ${id} not found`);
    }
    category.is_visible = visible;
    // category.is_visible = !category.is_visible;
    return this.categoryRepository.save(category);
  }

  // 获取所有类别（后台管理用，包含隐藏类别）
  async getAllCategories(
    page: number = 1,
    limit: number = 10,
  ): Promise<PaginatedCategoryPages> {
    // return this.categoryRepository.find();
    const [data, total] = await this.categoryRepository.findAndCount({
      skip: (page - 1) * limit,
      take: limit,
      order: { createdAt: 'DESC' }, // 按创建时间倒序
    });

    return {
      data,
      meta: {
        total,
        page,
        limit,
        totalPages: Math.ceil(total / limit),
      },
    };
  }

  // 获取可见类别（供前端调用）
  async getVisibleCategories(): Promise<Category[]> {
    return this.categoryRepository.find({ where: { is_visible: true } });
  }

  async getCategoryById(id: number): Promise<Category> {
    const category = await this.categoryRepository.findOne({ where: { id } });
    if (!category) {
      throw new NotFoundException(`Category with ID ${id} not found`);
    }
    return category;
  }
}
